#-*- coding: utf-8 -*-

from file.u2u import u2u
from file.gui import gui
from file.config import config
import threading

class main(object):
    def __init__(self, path):
        self.config = config(path)
        self.userstop = False
        self.u2u = u2u()
        self.u2u_init()
        self.gui = gui(self.handle_enter)
        self.gui.nick1 = self.config.nick1
        self.gui.nick2 = self.config.nick2

        self.lock = threading.Lock()

    def u2u_init(self):
        self.u2u.logchat = self.config.logchat
        self.u2u.nick1 = self.config.nick1
        self.u2u.nick2 = self.config.nick2
        self.u2u.autostop = self.config.autostop
        self.u2u.timeout = self.config.timeout
        if self.config.repeat:
            self.u2u.event_stopChat = self.handle_stop

    def command(self, txt):
        comm = {'1': self.start, '2':self.stop, '3':self.guiview}
        if txt in comm.iterkeys():
            comm[txt]()

    def start(self):
        self.userstop = False
        threading.Timer(2.0, self.u2u.start).start()

    def stop(self):
        self.userstop = True
        self.u2u.stop()

    def guiview(self):
        if self.u2u.isStart:
            self.gui.view()
        else:
            print u'Чат не запущен'

    def handle_stop(self):
        with self.lock:
            if not self.userstop:
                print u'Авто повтор'
                threading.Timer(5.0, self.start).start()


    def handle_enter(self, value, txt):
        nick = u'обоим'
        if value==1: nick = u'от '+self.u2u.nick1
        if value==2: nick = u'от '+self.u2u.nick2
        self.u2u.send(value, txt)
        self.u2u.log(u'(Бог написал %s): %s' % (nick, txt))